<template>
  <div>
    <!--查询-->
    <el-form :inline="true">
      <!--根据ystsn查询-->
      <el-form-item>
        <el-input placeholder="YSTSN" clearable v-model="searchDto.ystsn"></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchDto.date"
          align="right"
          type="daterange"
          start-placeholder="选择维修时间段"
          end-placeholder="选择维修时间段"
          range-separator="至"
          value-format="yyyy-MM-dd"
          format="yyyy 年 MM 月 dd 日"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="BatchApproveBtn">批量审批</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="exportLoading" @click="excelExport()">数据导出</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick(activeName)">
      <el-tab-pane label="待审批" name="unApprove">
        <custom-table
          :multipleSelection="true"
          :data="scrapList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :operationColumn="operationColumn"
          :pagination="pagination"
          @selection-change="selectionChange">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="已审批" name="alreadyApprove">
        <custom-table
          :data="alreadyScrapList"
          :columns="finishColumns"
          :tableLoadingFlag="finishTableLoadingFlag"
          :operationColumn="operationColumn1"
          :pagination="pagination1">
        </custom-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="报废审批" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="scrapDto" :rules="scrapRules" label-width="60px" ref="scrapForm">
        <el-form-item label="审批">
          <el-radio-group v-model.number="scrapDto.approvedResult">
            <el-radio-button label="0">同意</el-radio-button>
            <el-radio-button label="1">不同意</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因" prop="cause">
          <el-input v-model.trim="scrapDto.cause" placeholder="请输入原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onBtnCancel()">取消</el-button>
        <el-button type="primary" @click="onBtnSubmit()" v-no-more-click>确定</el-button>
      </div>
    </el-dialog>
    <!--报废详情-->
    <el-dialog title="报废详情" center :visible.sync="applyDetailVisible" wdith="100%" :close-on-click-modal="false">
      <el-steps align-center :active="applyStep" finish-status="success" :process-status="processStatus">
        <el-step title="申请报废"></el-step>
        <el-step title="审批"></el-step>
        <el-step title="报废入库"></el-step>
      </el-steps>
      <div v-if="applyStep>=1">
        <h4>审批结果：</h4>
        <custom-table
          :columns="columnDailogApprove"
          :data="applyApproveDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiGetScrapList, apiScrap, apiDownload, apiGetAlreadyScrapList, apiScrapListExport, apiBatchApproveScrap} from
      '@/api/approve/scrap'
  import {getUserId, getUserName} from '@/utils/token'
  import {parseTime} from '@/utils'
  import {apiGetFactoryScrapDetail} from '@/api/repairs/factory/index'
  import {downloadExcel} from "../../utils";

  export default {
    components: {
      CustomTable
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getScrapList(listQuery)
      this.getAlreadyScrapList(listQuery)
    },
    data () {
      return {
        // 页面标志量 0:未审批 1:已审批
        tab: 0,
        activeName: 'unApprove',
        tableLoadingFlag: false,          // 审批列表
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '返厂批次号', name: 'batch', align: 'center', width: '180'},
          {label: '返厂时间', name: 'backTime', align: 'center', formatter: this.formatTime, width: '180'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '城市', name: 'city', align: 'center'},
          {label: '生产厂商', name: 'brandName', align: 'center'},
          {label: '型号', name: 'modelName', align: 'center', width: '100'},
          {label: 'YSTEN', name: 'ystsn', align: 'center', width: '180'},
          {label: '维修时间', name: 'repairTime', align: 'center', width: '180'},
          {label: '责任归属', name: 'duty', align: 'center'},
          {label: '故障分类', name: 'faultType', align: 'center'},
          {label: '故障现象', name: 'faultAppearance', align: 'center'}
        ],
        // 待审批选择框
        selectionList: [],
        selectBatchApprove: '',
        scrapList: [],
        operationColumn: {
          width: '80',
          operations: [
            {name: '审批', callback: this.onBtnScrap},
            {name: '下载附件', callback: this.downloadFile, page: 'scrap'}
          ]
        },
        finishTableLoadingFlag: false,
        finishColumns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '返厂批次号', name: 'batch', align: 'center', width: '180'},
          {label: '返厂时间', name: 'backTime', align: 'center', formatter: this.formatTime, width: '180'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '城市', name: 'city', align: 'center'},
          {label: '生产厂商', name: 'brandName', align: 'center'},
          {label: '型号', name: 'modelName', align: 'center', width: '100'},
          {label: 'YSTEN', name: 'ystsn', align: 'center', width: '180'},
          {label: '维修时间', name: 'repairTime', align: 'center', width: '180'},
          {label: '责任归属', name: 'duty', align: 'center'},
          {label: '故障分类', name: 'faultType', align: 'center'},
          {label: '故障现象', name: 'faultAppearance', align: 'center'},
          {label: '审批状态', name: 'applicationStatus', align: 'center'}
        ],
        alreadyScrapList: [],
        // 表单操作栏
        operationColumn1: {
          width: '80',
          operations: [
            {name: '详情', callback: this.getDetailSelfApply},
            {name: '下载附件', callback: this.downloadFile, page: 'scrap'}
          ]
        },
        columnDailogApprove: [
          {label: '审批人', name: 'name', width: '100', align: 'center'},
          {label: '审批时间', name: 'time', width: '160', align: 'center', formatter: this.formatTime},
          {label: '审批结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        processStatus: 'wait',
        applyStep: 0,
        applyApproveDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        // 申请步骤条默认隐藏
        applyDetailVisible: false,
        dialogVisible: false,             // 审批模态框
        // 查询Dto
        searchDto: {
          ystsn: '',
          date: ''
        },
        scrapDto: {
          id: '',
          approverId: '',
          approverName: '',
          approvedResult: 0,
          cause: '',
          ystsn: '',
          batch: '',
          selectBatchApprove: 0,
          applicationIds: [],
          ystsns: [],
          batches: []
        },
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          }
        },
        scrapRules: {
          cause: [
            {
              validator: (rule, value, callback) => {
                if (this.scrapDto.approvedResult === 1 && value === '') {
                  callback(new Error('请输入不同意原因'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            },
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ]
        },
        pagination: this.getData(this.getScrapList),
        pagination1: this.getData(this.getAlreadyScrapList),
        exportLoading: false
      }
    },
    methods: {
      selectionChange (val) {
        this.selectionList = val
      },
      BatchApproveBtn () {
        if (this.selectionList === undefined || this.selectionList.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择审批设备',
            type: 'warn'
          })
          return
        }
        let num = this.selectionList.length
        for (let i = 0; i < num; i++) {
          this.scrapDto.applicationIds.push(this.selectionList[i].id)
          this.scrapDto.ystsns.push(this.selectionList[i].ystsn)
          this.scrapDto.batches.push(this.selectionList[i].batch)
          this.scrapDto.approverName = getUserName()
          this.scrapDto.approverId = getUserId()
          this.scrapDto.selectBatchApprove = 1
          this.dialogVisible = true
        }
      },
      // 切换tab
      handleClick (activeName) {
        if (activeName === 'unApprove') {
          this.tab = 0
          this.searchList()
        } else if (activeName === 'alreadyApprove') {
          this.tab = 1
          this.searchList()
        }
      },
      // 按条件查询
      searchList () {
        let listQuery = {
          ystsn: this.searchDto.ystsn,
          repairBeginTime: this.searchDto.date === null ? '' : this.searchDto.date[0],
          repairEndTime: this.searchDto.date === null ? '' : this.searchDto.date[1]
        }
        if (this.tab === 0) {
          this.getScrapList(listQuery)
        } else if (this.tab === 1) {
          this.getAlreadyScrapList(listQuery)
        }
      },
      getScrapList (listQuery) {
        if (listQuery.ystsn === undefined) {
          listQuery.ystsn = this.searchDto.ystsn
        }
        if (listQuery.repairBeginTime === undefined) {
          listQuery.repairBeginTime = this.searchDto.date === null ? '' : this.searchDto.date[0]
        }
        if (listQuery.repairEndTime === undefined) {
          listQuery.repairEndTime = this.searchDto.date === null ? '' : this.searchDto.date[1]
        }
        listQuery.pageNumber = this.pagination.currentPage
        listQuery.pageSize = this.pagination.pageSize
        this.tableLoadingFlag = true
        apiGetScrapList(listQuery).then(response => {
          this.scrapList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getAlreadyScrapList (listQuery) {
        if (listQuery.ystsn === undefined) {
          listQuery.ystsn = this.searchDto.ystsn
        }
        if (listQuery.repairBeginTime === undefined) {
          listQuery.repairBeginTime = this.searchDto.date === null ? '' : this.searchDto.date[0]
        }
        if (listQuery.repairEndTime === undefined) {
          listQuery.repairEndTime = this.searchDto.date === null ? '' : this.searchDto.date[1]
        }
        listQuery.pageNumber = this.pagination1.currentPage
        listQuery.pageSize = this.pagination1.pageSize
        this.finishTableLoadingFlag = true
        apiGetAlreadyScrapList(listQuery).then(response => {
          this.alreadyScrapList = response.data
          this.pagination1.totalRecords = response.totalRecords
          this.finishTableLoadingFlag = false
        }).catch(() => {
          this.finishTableLoadingFlag = false
        })
      },
      // 数据导出
      excelExport () {
        this.exportLoading = true
        let listQuery = {
          ystsn: this.searchDto.ystsn,
          repairBeginTime: this.searchDto.date === null ? '' : this.searchDto.date[0],
          repairEndTime: this.searchDto.date === null ? '' : this.searchDto.date[1],
          repairResult: this.activeName === 'unApprove' ? 4 : 5
        }
        apiScrapListExport(listQuery).then(response => {
          downloadExcel(response.data, '自有售后报废信息导出表')
          this.exportLoading = false
        }).catch(() => {
          this.exportLoading = false
        })
      },
      getDetailSelfApply (row) {
        apiGetFactoryScrapDetail(row.id).then(response => {
          if (response.data === undefined || response.data === null) {
            // 已提交申请，待审核
            this.applyStep = 0
            this.processStatus = 'success'
          } else {
            if (response.data.result === 1) {
              this.applyStep = 1
              this.processStatus = 'error'
            } else if (response.data.result === 0) {
              // 判断是否在报废库中，如果SN号存在，则默认已经返还办事处
              if (response.inScrap === true) {
                this.applyStep = 2
                this.processStatus = 'success'
              } else {
                // 激活active
                this.applyStep = 1.1
                this.processStatus = 'success'
              }
            }
          }
          if (this.applyStep >= 1) {
            this.applyApproveDetail[0].name = response.data.name
            this.applyApproveDetail[0].time = response.data.approveDate
            this.applyApproveDetail[0].result = response.data.result
            this.applyApproveDetail[0].reason = response.data.cause
          }
          this.applyDetailVisible = true
        })
      },
      onBtnScrap (row) {        // 审批按钮事件,弹出审批对话框
        let dto = this.scrapDto
        dto.approvedResult = 0
        dto.applicationId = row.id
        dto.approverId = getUserId()
        dto.approverName = getUserName()
        dto.ystsn = row.ystsn
        dto.batch = row.batch
        this.dialogVisible = true
      },
      downloadFile (row) {
        let fileNameArr = row.filePath.split('.')
        let paramsPost = {
          id: row.id
        }
        if (fileNameArr[fileNameArr.length - 1] === 'xlsx') {
          apiDownload(paramsPost).then(response => {
            let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
            window.location.href = URL.createObjectURL(blob)
          }).catch(() => {
          })
        } else if (fileNameArr[fileNameArr.length - 1] === 'zip') {
          apiDownload(paramsPost).then(response => {
            let blob = new Blob([response.data], {type: 'application/x-zip-compressed'})
            window.location.href = URL.createObjectURL(blob)
          }).catch(() => {
          })
        }
      },
      onBtnSubmit () {      // 审批模态框中确定按钮事件
        if (this.scrapDto.selectBatchApprove === 0) {
          this.$refs['scrapForm'].validate((valid) => {
            if (valid) {
              // 审批接口
              apiScrap(this.scrapDto).then(() => {
                this.$message({
                  showClose: true,
                  message: '审批成功！',
                  type: 'success'
                })
                let listQuery = {}
                this.getScrapList(listQuery)
                this.onBtnCancel()
              })
            } else {
              return false
            }
          })
        }
        if (this.scrapDto.selectBatchApprove === 1) {
          this.$refs['scrapForm'].validate((valid) => {
            if (valid) {
              // 审批接口
              apiBatchApproveScrap(this.scrapDto).then(() => {
                this.$message({
                  showClose: true,
                  message: '审批成功！',
                  type: 'success'
                })
                let listQuery = {}
                this.getScrapList(listQuery)
                this.onBtnCancel()
              })
            } else {
              return false
            }
          })
        }
      },
      onBtnCancel () {     // 审批模态框中取消按钮事件
        this.scrapDto.batches = []
        this.scrapDto.applicationIds = []
        this.scrapDto.ystsns = []
        this.dialogVisible = false
        this.$refs['scrapForm'].resetFields()
      },
      formatTime (row, column, cellValue) {
        return parseTime(cellValue)
      },
      formatStatus (row, column, cellValue) {
        if (cellValue === 1) {
          return '不通过'
        }
        return '通过'
      }
    }
  }
</script>
